var $businessTable = $('#businessTable');//表单
var dateType = '';//时间切换

$(function(){
    businessTableInit();//表单初始化
    businessLineData('');//折线图数据初识化
    businessPieInitData('');//饼状图数据初识化
})

//防止表头与表格不对齐
$(window).resize(function () {
    $businessTable.bootstrapTable('resetView');
});

function businessTableInit(){
    //先销毁表格
    $businessTable.bootstrapTable('destroy');
    $businessTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/opportunity/selectOppStatistics',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'formId',
        idField: 'formId',
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 4,         // 左侧固定列
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'customerId', visible: false},
            {title: '商机名称', field: 'opportunityTitle',align: 'left', valign: 'middle'},
            {title: '所属客户', field: 'customerName', align: 'left', valign: 'middle'},
            {title: '建立时间', field: 'createTm', align: 'left', valign: 'middle'},
            {title: '跟进天数', field: 'followNumber', align: 'left', valign: 'middle'},
            {title: '操作', field: 'operate', align: 'right', events: operateEvents, formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000"){
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    })
}

/**
 * 普通查询参数
 */
function queryParams(params){
    params.pageIndex = (params.offset / params.limit) + 1;//页码
    params.pageSize = params.limit;//每页条数
    params.sortName = params.sort;//排序列命
    params.sortOrder = params.order;//排序规则
    params.dateType = dateType, //时间
    params.bs = 1;  //0管理端 1用户端
    return params;
}

/**
 * 自定义操作列内容
 */
function genderOpt(){
    var btnHtml = '<button type="button" class="btn btn-default"><i class="mdi mdi-target"></i>指标检测</button>';
    btnHtml += '<button type="button" class="btn btn-default"><i class="mdi mdi-message-text-outline"></i>话术支持</button>';
    btnHtml += '<button type="button" class="btn btn-default"><i class="mdi mdi-chart-donut"></i>方案支持</button>';

    return btnHtml;
    return [
        '<a type="button" id="detail" class="btn btn-xs btn-default m-r-5 show-btn" title="指标检测" data-toggle="tooltip">指标检测</a>',
        '<a type="button" id="detail" class="btn btn-xs btn-default m-r-5 show-btn" title="话术支持" data-toggle="tooltip">话术支持</a>',
        '<a type="button" id="sign" class="btn btn-xs btn-default m-r-5 show-btn" title="方案支持" data-toggle="tooltip">方案支持</a>'
    ].join('');
}
window.operateEvents = {

}

/**
 * 切换时间选项
 */
function selectTime(time) {
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.month').removeClass('active-second');
        $('.quarter').removeClass('active-second');
        $('.year').removeClass('active-second');
        $("#dateType").val("all");
        businessLineData('');//折线图
        businessPieInitData('');//饼状图
        dateType = '';
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.quarter').removeClass('active-second');
        $('.year').removeClass('active-second');
        $("#dateType").val("month");
        businessLineData('thisMonth')//折线图
        businessPieInitData('thisMonth');//饼状图
        dateType = 'thisMonth';
    }
    if (time == 'quarter') {//本季度
        $('.quarter').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.year').removeClass('active-second');
        $("#dateType").val("thisWeek");
        businessLineData('thisQuarter')//折线图
        businessPieInitData('thisQuarter');//饼状图
        dateType = 'thisQuarter'
    }
    if (time == 'year') {//本年度
        $('.year').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.quarter').removeClass('active-second');
        $("#dateType").val("thisMonth");
        businessLineData('thisYear')//折线图
        businessPieInitData('thisYear');//饼状图
        dateType = 'thisYear'
    }
    $businessTable.bootstrapTable('refreshOptions', {pageNumber: 1,queryParams: queryParams});
}

/**
 * 折线图数据初始化
 */
function businessLineData(dateType) {
    var jsonData = {
        dateType:dateType,
        bs:'1'
    };
    $.ajax({
        url: "/opportunity/oppStatusStatistics",
        async: true,
        data: JSON.stringify(jsonData),
        type: "POST",
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        success: function (result) {
            if(result.code == "000000"){
                businessLineInit('businessLine',result.data);//商机折线图
            }
        },
        error: function (res){
            alert('请求失败')
        }
    })
}

/**
 * 饼状图数据初始化
 */
function businessPieInitData(dateType){
    $.ajax({
        url: "/opportunity/oppProductStatistics",
        async: true,
        data: {
            dateType:dateType,
            bs:'1'
        },
        type: "POST",
        dataType: "json",
        success: function (result) {
            if(result.code == "000000"){
                var newArr = result.data.map(item => ({
                    name: item.productName,
                    value: item.proportion,
                }))
                businessPieInit('businessPie',newArr)//商机饼状图
            }
        },
        error: function (res){
            alert('请求失败')
        }
    })
}


/**
 * 折线图初始化
 */
function businessLineInit(id,data){
    let dom = document.getElementById(id);
    let myChart = echarts.init(dom);
    const color = ['#6699ff']
    let option = {
        tooltip: {
            trigger: 'axis',

            extraCssText: 'font-size:14px;line-height:24px;color:#fff;background:#212947;opacity: 0.9;padding:10px 20px;box-shadow:0 0 3px rgba(0, 0, 0, 0.2)',
            formatter: function(params) {
                let html = `<span style="">${params[0].axisValue}</span>`
                params.forEach(v => {
                    html += `<div>
<span style="display:inline-block;color: #999999;border-radius:10px;width:10px;height:10px;border: 2px solid #FFFFFF;background-color:${color[v.componentIndex]};"></span>
<span style="color:${color[v.componentIndex]};font-size:18px;font-weight:700;padding-left: 6px;">${v.value}</span>`
                })
                return html
            }
        },
        xAxis: {
            type: 'category',
            data: ['初步洽谈', '需求确定', '方案报价', '谈判', '洽谈合同', '赢单', '输单'],
            boundaryGap: true,
            axisLine: {
                lineStyle: {
                    color: '#ddd'
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#999999',
                padding: [8, 0, 0, 0]
            }
        },
        yAxis: {
            type: 'value',
            axisLine: {
                lineStyle: {
                    color: '#ddd'
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#999',
                padding: [0, 8, 0, 0]
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#f3f3f3',
                    type: 'dotted',
                    width: 1
                }
            }
        },
        series: [{
            data: data,
            type: 'line',
            smooth: true,
            lineStyle: {
                color: '#6699ff'
            },
            areaStyle: {
                color: '#6699ff',
                opacity: 0.8
            },
            itemStyle: {
                normal: {
                    color: '#6699ff',
                    borderColor: '#6699ff'
                }
            },
        }]
    };
    myChart.setOption(option);
    window.addEventListener("resize",function(){
        myChart.resize();
    });
}
/**
 * 饼状图图初始化
 */
function businessPieInit(id,data){
    let dom = document.getElementById(id);
    let myChart = echarts.init(dom);
    let option = {
        // title: {
        //     text: '商品产品比重',
        //     left: 'center'
        // },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {d}%',
        },
        legend: {
            type: 'scroll',
            orient: "vertical",
            icon: "rect",
            top: "middle",
            right: "10%",
            height: '60%'
        },
        color: ['#a1e5ce', '#b2cdff', '#6699ff', '#52cca3', '#9580ff', '#bfb2ff', '#a1e5ce', '#b2cdff', '#6699ff', '#52cca3'],
        series: [
            {
                name: '商品产品比重',
                type: 'pie',
                radius: '50%',
                center: ['30%', '50%'],
                data: data,
                /*itemStyle: {
                    color: (params) => {
                        return ['#a1e5ce', '#b2cdff', '#6699ff', '#52cca3', '#9580ff', '#bfb2ff', '#a1e5ce', '#b2cdff', '#6699ff', '#52cca3'][params.dataIndex]
                    }
                },*/
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ],
        grid:{
            right:0,
        }
    };
    myChart.setOption(option);
    window.addEventListener("resize",function(){
        myChart.resize();
    });
}